package com.mall.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 * @Author： wz
 * @Date: 2019-09-16 00:03
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

	@Override
	public boolean isAsync() {
		return false;
	}

	@Override
	@Transactional
	public boolean handle(TransHandlerContext context) {

		//向下转型，转换上下文
		CreateOrderContext createOrderContext = (CreateOrderContext) context;
		//获得购物车内商品的ID
		List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
		//将购物车内商品的ID赋值给createOrderContext的商品ID
//		List<Long> buyProductIds = createOrderContext.getBuyProductIds();
		List<Long> buyProductIds = new ArrayList<>();
		for (CartProductDto cartProductDto : cartProductDtoList) {
			buyProductIds.add(cartProductDto.getProductId());
		}
		//扣减库存
		for (CartProductDto cartProductDto : cartProductDtoList) {
			Stock stock = new Stock();
			//获得购买的数量
			Long productNum = cartProductDto.getProductNum();
			stock.setLockCount(productNum.intValue());
			stock.setStockCount(-productNum);
			stock.setItemId(cartProductDto.getProductId());
			//在数据库扣减库存
			stockMapper.updateStock(stock);
		}

        return true;
	}
}
